package com.ph.website.home.service.impl;

import com.ph.website.home.base.common.CommonResult;
import com.ph.website.home.base.common.Ref;
import com.ph.website.home.base.component.GlobalParam;
import com.ph.website.home.entity.HomeCert;
import com.ph.website.home.mapper.HomeCertMapper;
import com.ph.website.home.param.HomeCertParam;
import com.ph.website.home.service.IHomeCertService;
import com.ph.website.home.vo.HomeCertVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class HomeCertServiceImpl implements IHomeCertService {

    @Resource
    private HomeCertMapper homeCertMapper;
    @Resource
    private GlobalParam globalParam;

    /**获取所有的证书*/
    public CommonResult listAll(){

        List<HomeCert> list = homeCertMapper.listAll();
        List<HomeCertVo.ListAllVo> vos = new ArrayList<>();
        for(HomeCert cert : list){
            HomeCertVo.ListAllVo vo = new HomeCertVo.ListAllVo();
            vo.setCertId(cert.getId());
            vo.setImgUrl(cert.getImgUrl());
            vo.setOrderNum(cert.getOrderNum());
            vo.setUsable(cert.getUsable());
            vo.setPrefix(globalParam.getImg().getPrefix());
            vo.setImgViewUrl(globalParam.getImg().getPrefix() + cert.getImgUrl());
            vos.add(vo);
        }
        return Ref.ok(vos);
    }

    /**新增证书*/
    public CommonResult add(HomeCertParam.AddParam param){
        HomeCert cert = new HomeCert();
        cert.setCreateTime(new Date());
        cert.setImgUrl(param.getImgUrl());
        cert.setOrderNum(param.getOrderNum());
        cert.setUsable(param.getUsable());
        homeCertMapper.insert(cert);
        return Ref.ok();
    }

    /**修改证书*/
    public CommonResult modify(HomeCertParam.ModifyParam param){
        HomeCert cert = homeCertMapper.selectById(param.getCertId());
        if(cert==null){
            return Ref.error("错误的证书编号");
        }
        cert.setUsable(param.getUsable());
        cert.setOrderNum(param.getOrderNum());
        cert.setImgUrl(param.getImgUrl());
        homeCertMapper.updateById(cert);
        return Ref.ok();
    }

    /**删除证书*/
    public CommonResult delete(HomeCertParam.DeleteParam param){
        homeCertMapper.deleteById(param.getCertId());
        return Ref.ok();
    }
}
